package com.bwsoft.portal.service.impl;

import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.util.Constant;
import com.bwsoft.portal.service.AccountService;
import com.bwsoft.util.UploadFileUtil;

@Service(AccountService.NAME)
public class AccountServiceImpl extends PortalBaseServiceImpl implements
	AccountService {
	private static Logger LOG = Logger.getLogger(AccountServiceImpl.class);

	@Override
	public Account findAccount(Integer accountId) {
		return accountDao.findById(accountId);
	}

	@Override
	public Account findAccountByCompName(String compName) {
		List<Account> accounts = accountDao.findByHql("from Account where compName=?", compName);
		if (accounts.size() > 0)
			return accounts.get(0);
		else
			return null;
	}

	@Override
	public ResponsePojo update(Account account, File headImgURL, String headImgURLName) {
		ResponsePojo rp = new ResponsePojo();
		try {
			if(headImgURLName != null && !"".equals(headImgURLName)){
				Calendar now = Calendar.getInstance();
				String headImgRealpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_HEADIMG)+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1);
				String headImgRealName=null ;
				headImgRealName=UUID.randomUUID().toString()+headImgURLName.substring(headImgURLName.lastIndexOf('.'), headImgURLName.length());
				UploadFileUtil.uploadOneFile(headImgRealName, headImgURL, headImgRealpath);
				account.setHeadImgURL(Constant.PATH_IMG_HEADIMG+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+headImgRealName);
			} else {
				account.setHeadImgURL(accountDao.findById(account.getAccountId()).getHeadImgURL());
			}
			
			accountDao.saveOrUpdate(account);
			rp.setErrcode(0);
			rp.setErrmsg("更新成功！");
		} catch (Exception e) {
			rp.setErrcode(12);
			rp.setErrmsg("保存失败");
			LOG.info(e);
		}
		return rp;
	}

	@Override
	public boolean checkAccount(String account, Integer accountId) {
		List<Account> accounts = (List<Account>)accountDao.findByHql("from Account where account=? and accountId!=?", account, accountId);
		if (accounts.size() > 0)
			return true;
		else
			return false;
	}
}
